<?php

/**
 * Example to dumping data into XML using Stream_Iterate as stream
 * and a formatter class
 *
 * PHP version 5
 *
 * @category  Stream
 * @package   Stream_Iterate
 * @author    Philippe Jausions <Philippe.Jausions@11abacus.com>
 * @copyright 2008 11abacus / Philippe Jausions
 * @license   http://www.opensource.org/licenses/bsd-license.php New BSD
 * @link      http://pear.11abacus.com/package/Stream_Iterate
 */

/**
 * Required packages
 */
require_once 'Stream/Iterate.php';
require_once 'Stream/Iterate/FormatterInterface.php';

/**
 * Formatter helper class
 */
class myXMLFormat implements Stream_Iterate_FormatterInterface
{
    /**
     * Prints the XML header
     * 
     * @param mixed $data Data of the first iteration
     *
     * @return string XML string
     */
    public function onFirstIteration($data)
    {
        return '<?xml version="1.0"?><dataset>';
    }
    
    /**
     * Defines an XML "printer"
     *
     * @param mixed   $key       Key of iteration
     * @param array   $value     Value of iteration
     * @param integer $iteration Iteration counter (zero-based)
     *
     * @return string XML string
     */
    public function formatKeyPair($key, $value, $iteration)
    {
        if (empty($value)) {
            return '';
        }
        $xml = '<set counter="'.$iteration.'">';
        foreach ($value as $header => $data) {
            $xml .= '<'.$header.'>'
                    .htmlspecialchars($data)
                    .'</'.$header.'>';
        }
        return $xml."</set>\n";
    }
    
    /**
     * Prints the XML footer
     *
     * @param integer $iteration Last iteration count
     * 
     * @return string XML string
     */
    public function onLastIteration($iteration)
    {
        return '</dataset>';
    }
}

/**
 * Main
 */
stream_wrapper_register('foreach', 'Stream_Iterate');

$data = array(array('firstname' => 'John',
                    'lastname'  => 'Doe',
                    'city'      => 'Towneville'),
              array('lastname'  => 'Doe',
                    'city'      => 'Citybourg',
                    'firstname' => 'Jane'));

$context = stream_context_create(array('foreach' => array('data' => $data)));

// By specifying the class name of the formatter, an instance will be
// created automatically...
echo file_get_contents('foreach://data?formatter=myXMLFormat', 0, $context);

echo "\n\n";

// ...otherwise, specify the formatter instance in the context.
$context = stream_context_create(array(
	'foreach' => array(
		'data' => $data,
        'formatter' => new myXMLFormat(),
    )
));

echo file_get_contents('foreach://data', 0, $context);

?>